package com.cskaoyan.javase.practice.stage6.utils;

import java.io.*;

/**
 * @program: little-practice
 * @description: read and store file
 * @author: Keyu Li
 * @create: 2021-09-10 23:08
 **/

public class FileUtiles {
    static BufferedReader reader;
    static BufferedWriter writer;

    private FileUtiles() {

    }

    public static String[] getAllStuInfofromFile(File file) throws IOException {
        /**
         * 规定：文件第一行存储学生总数，后面每一行存储学生信息
         * 1. 提取第一行，读取学生人数，确定储存数组大小。
         * 2. 如果文件为空，或者学生数为0，则返回null
         * 3. 提取后续行，存入数组
         */
        reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();
        int count;
        if (line == null) return null;
        if ((count = StringUtils.parseToStuNum(line)) <= 0) return null;

        String[] stus = new String[count];
        int i = 0;
        while ((line = reader.readLine()) != null) {
            stus[i++] = line;
        }
        if (i!=count) System.out.println("Wrong Count Info!");
        reader.close();
        return stus;
    }

    public static boolean writeStuInfotoFile(File file, String[] stu) {
        try {
            writer = new BufferedWriter(new FileWriter(file));
            // 判断stu是否为空，如果空，则写入学生数目0
            if (stu==null){
                writer.write("student total number: 0");
                return false;
            }
            // 写入第一行
            writer.write("student total number: " + stu.length);
            writer.newLine();
            for (String s : stu) {
                writer.write(s);
                writer.newLine();
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
